package com.task.submitter.controllers;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.users.User;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ServingUrlOptions;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.com.google.api.client.util.Lists;
import com.task.submitter.dto.StoredImageDto;

@Controller
public class ImageUploadController extends BaseController {
	
	
	@RequestMapping("/task/image")
    public ModelAndView images(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String email = getEmail(request, response);
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
        ModelAndView mav = new ModelAndView("upload");
        String uploadDir = blobstoreService.createUploadUrl("/task/image/upload");
        mav.addObject("blobUploadRedirect", uploadDir);
        mav.addObject("email", email);
        mav.addObject("images", getStoredImages(email));
        
        return mav;
    }
	
	@RequestMapping("/task/image/upload")
    public String uploadFile(HttpServletRequest request) {
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
		List<BlobKey> blobKey = blobs.get("myFile");
		String nameId = request.getParameter("nameId");
		User user=  UserServiceFactory.getUserService().getCurrentUser();
		Key userCtxKey = KeyFactory.createKey("UserContext", user.getEmail());
		Entity imgKey = new Entity("ImgKey", userCtxKey);
		imgKey.setProperty("key", blobKey.get(0).getKeyString());
		imgKey.setProperty("nameId", nameId);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(imgKey);

        return "redirect:/task/image";
    }
	
	public List<StoredImageDto> getStoredImages(String user){
		List<StoredImageDto> dtos = Lists.newArrayList();
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    Key userCtxKey = KeyFactory.createKey("UserContext", user);
	    Query query = new Query("ImgKey", userCtxKey);
	    List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
		
	    for(Entity result : results){
	    	ImagesService imagesService = ImagesServiceFactory.getImagesService();
	    	String blobKeyString = String.valueOf(result.getProperty("key"));
	    	BlobKey key = new BlobKey(blobKeyString);
			ServingUrlOptions options = ServingUrlOptions.Builder.withBlobKey(key);
			String imageUrl = imagesService.getServingUrl(options);
			StoredImageDto dto = new StoredImageDto();
			dto.setBlobKey(blobKeyString);
			dto.setUrl(imageUrl);
			dto.setNameId(String.valueOf(result.getProperty("nameId")));
			dtos.add(dto);
	    }
		
		return dtos;
	}
	
}
